var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const cors = require('cors');
const helmet = require('helmet');
const fs = require('fs');
// 引入自定义模块
const {stopIP,apiProxy} = require("./utils/index.js");
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var downloadRouter = require('./routes/download');

var app = express();

const moduleAlias = require('module-alias');
// 定义别名映射  
const aliases = {
  '@': path.resolve(__dirname),
  '@app': path.resolve(__dirname, 'app'),
  '@core': path.resolve(__dirname, 'core'), 
  '@validators': path.resolve(__dirname, 'app/validators'),
  "@middlewares": path.resolve(__dirname,"middlewares"),
  "@api": path.resolve(__dirname,"app/api"),
  "@dao": path.resolve(__dirname,"app/dao"),
  "@lib": path.resolve(__dirname,"app/lib"),
  "@models": path.resolve(__dirname,"app/models"),
  "@service": path.resolve(__dirname,"app/service"),
};

// 为每个别名设置路径  
Object.keys(aliases).forEach((alias) => {
  moduleAlias.addAlias(alias, aliases[alias]);
});

// view engine setup 模板引擎
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(helmet()); //设置安全HTTP头中间件
app.use(cors()); //跨域中间件
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public'))); //配置静态资源 访问时不需要出现该文件夹
// 也可以出现多个静态资源文件夹 如
// app.use(express.static(path.join(__dirname, 'static'))); //配置另外一个静态资源文件夹

// 封禁IP中间件
app.use(stopIP)
// 挂载代理中间件到 '/api' 路由  
app.use('/api', apiProxy); 
app.use('/', indexRouter);
app.use('/download', downloadRouter);
app.use('/users', usersRouter); //可设置路由前缀

// catch 404 and forward to error handler
// 错误中间件放到最后匹配
app.use(function(req, res, next) {
  next(createError(404));
});
// 事件循环测试
console.log("start");
setImmediate(() => {
  console.log("setImmediate");
})
process.nextTick(()=>{
  console.log("nextTick");
})
fs.readFile("./readme.md",(err, data) => {
  console.log("readFile");
  setTimeout(() => {
    console.log("setTimeout_no");
  });
  setTimeout(() => {
    console.log("setTimeout0");
  },0);
})
console.log("end");

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
